package com.ak.es.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;

/**
 * @program: AK-ES
 * @description: 自动配置注入restHighLevelClient
 * @author: AK
 * @create: 2019-01-07 14:09
 **/
@Configuration
@ComponentScan("com.ak.es")
public class ElasticSearchConfiguration {

	@Value("${spring.data.elasticsearch.cluster-nodes}")
	private String host;

	private RestHighLevelClient restHighLevelClient;

	@Bean(destroyMethod = "close") // 这个close是调用RestHighLevelClient中的close
	@Scope("singleton")
	public RestHighLevelClient createInstance() {
		try {
			if (StringUtils.isEmpty(host)) {
				return null;
			}
			String[] hosts = host.split(",");
			HttpHost[] httpHosts = new HttpHost[hosts.length];
			for (int i = 0; i < httpHosts.length; i++) {
				String h = hosts[i];
				httpHosts[i] = new HttpHost(h.split(":")[0], Integer.parseInt(h.split(":")[1]), "http");
			}
			restHighLevelClient = new RestHighLevelClient(RestClient.builder(httpHosts));
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return restHighLevelClient;
	}
}
